#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# Author:    LJ
# Email:     admin@attacker.club
# Date:      18-3-27
# Description: 
# python cron.py  -c 21:00 -n test脚本  -a logan -d "test"     -s  /root/test.sh
"""

import re
import os
import re
import sys
import shlex
import time
import argparse
import platform
import logging
import subprocess
import logging
from logging.handlers import RotatingFileHandler
import subprocess
import json
import requests


try:
    import configparser
except:
    import ConfigParser as configparser


def bash(cmd):
    """
    执行执行bash命令
    """
    return shlex.os.system(cmd)


def shell(cmd):
    """ shell执行  """
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
    results = p.communicate()[0]
    return results.decode()


def run_shell(cmd):
    """
    执行系统命令
    """
    (status, output) = subprocess.getstatusoutput(cmd)
    context = {
        'status': status,
        'output': output,
    }
    return context


def lan_ip():
    nic_info = []
    for nic, addrs in psutil.net_if_addrs().items():
        if ":" not in addrs[0].address:
            if addrs[0].address != "127.0.0.1" and nic.find('docker') == -1 and nic.find('vm') == -1 and nic.find('docker') == -1 and nic.find('tun') == -1:
                nic_info.append(addrs[0].address)
    return nic_info


def file_io(path, method, content):
    """ 文件写入  """
    with open(path, method) as f:
        f.write(content)


def found_ip(content):
    """ 提取包含的ip,生成列表 """
    iplist = re.findall(
        r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b", content)
    if iplist:
        return iplist


class LoggerLog:
    def __init__(self, name=__name__):
        """
        实例化LoggerFactory类时的构造函数
        :param name:
        """
        # 实例化logging
        self.logger = logging.getLogger(name)
        # 输出的日志格式
        self.formatter = formatter = logging.Formatter(
            '%(asctime)s %(name)s: %(levelname)s %(message)s')

    def create_logger(self):
        """
        构造一个日志对象
        """
        # 设置日志级别
        self.logger.setLevel(logging.DEBUG)
        # 设置日志输出的文件
        os.makedirs('logs', exist_ok=True)
        handle = logging.FileHandler('./logs/scripts.log')
        # 输出到日志文件的日志级别
        handle.setLevel(logging.INFO)
        handle.setFormatter(self.formatter)
        self.logger.addHandler(handle)
        # 输出到控制台的显示信息
        console = logging.StreamHandler()
        console.setLevel(logging.DEBUG)
        console.setFormatter(self.formatter)
        self.logger.addHandler(console)


def parse_args():

    parser = argparse.ArgumentParser(
        usage="lazy tools",
        description="脚本工具",
        add_help=False,
        formatter_class=lambda prog: argparse.RawTextHelpFormatter(
            prog, max_help_position=50)
    )
    parser.add_argument("--help",
                        action="help",
                        help="查看帮助信息")

    # 指定-v可选参数时，-v等于True，否则为False
    parser.add_argument("--uninstall",
                        action="store_true",
                        help="卸载")

    parser.add_argument("-n", "--name",
                        help="脚本名称")

    parser.add_argument("-a", "--author",
                        help="author")
    parser.add_argument("-d", "--desc",
                        help="desc")
    parser.add_argument("-c", "--crond_time",
                        help="定时时间")
    parser.add_argument("--ip",
                        help="ip")

    parser.add_argument('-t', '--type',
                        # required=True,  # (必备参数)
                        help="类型")

    parser.add_argument('-u', '--user',
                        help='用户')
    parser.add_argument('-p', '--passwd',
                        help='密码')
    parser.add_argument('-s', '--source', help="脚本文件路径")

    args = parser.parse_args()
    # print("打印所有变量",vars(args))
    return args


class Webapi():
    def __init__(self, username, password, data):
        self.username = username
        self.password = password
        self.loginurl = loginurl
        self.posturl = posturl
        self.data = data

    def get_token(self):
        """
        获取token
        """
        Data = {
            "username": self.username,
            "password": self.password
        }

        res = requests.post(self.loginurl, Data)
        # print(res.json())
        token = res.json()['data']['token']
        return token

    def tj(self):
        headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": "Token " + self.get_token()
        }

        ret = requests.post(url=self.posturl, data=self.data, headers=headers)
        print(ret.url)
        print(ret.text, ret.status_code)
        return ret


def print_json(data):
    data = data
    ret = json.dumps(data)
    print(ret)
    return ret


if __name__ == '__main__':
    start_time = time.strftime(
        "%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
    version = '1.0.0'

    loginurl = "http://10.88.0.157/api/oauth/login"
    posturl = "http://10.88.0.157/api/task/backupcrond"
    username = "OperatorCmdb"
    password = "TzCmdb#dingtone"

    if len(sys.argv) == 1:
        """ 如果没有参数则查看帮助信息 """
        sys.argv.append("--help")
        args = parse_args()

    args = parse_args()

    # result = run_shell(args.source)  # 执行shell
    res = bash(args.source)  # 执行cmd

    result = {}
    if res == 0:
        result["status"] = 0
        result["output"] = "successful"
    else:
        result["status"] = 1
        result["output"] = "failure"

    end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))

    data = {'script_name': args.name, 'crond_time': args.crond_time, 'script_author': args.author, 'script_desc': args.desc, 'run_host': args.ip, 'start_time': start_time,
            'end_time': end_time, 'result_status': result["status"], "result_msg": result["output"]}
    # data = {
    #     "script_name": "备份脚本",
    #     "crond_time": "AM 09",
    #     "script_author": "Logan",
    #     "script_desc": "测试",
    #     "run_host": "172.16.0.181",
    #     "start_time": "2021-01-28 23:23:06",
    #     "end_time": "2021-01-28 23:23:06",
    #     "result_status": "0",
    #     "result_msg": "xxxxx"
    # }
    print_json(data)  # 打印数据
    req = Webapi(username, password, data)
    req.tj()  # 提交数据到cmdb

    # Log = LoggerLog("demo")
    # Log.create_logger()
    # Log.logger.info('这是测试INFO输出')
    # # debug,warning,error

    # s = shell('curl -s ifconfig.io')
    # Log.logger.info(s)
    # print(s, type(s))
    # file_io('logs/file.txt', 'w', s)
